package net.miranti.persistence;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class PersistenceUtils {
	private static Map<String, EntityManagerFactory> persistenceUnitMap = new HashMap();
	
	public static EntityManagerFactory getEntityManagerFactory(String unit) {
		EntityManagerFactory res = persistenceUnitMap.get(unit);
		if(res==null) {
			res = Persistence.createEntityManagerFactory(unit);
			persistenceUnitMap.put(unit, res);
		}
		return res;
	}
	
	public static void close(String unit) {
		EntityManagerFactory emf = persistenceUnitMap.get(unit);
		if (emf!=null)
			emf.close();
	}
	
	public static void closeAll() {
		for (EntityManagerFactory emf : persistenceUnitMap.values())
			emf.close();
	}

	public static EntityManager createEntityManager(String unit) {
		return getEntityManagerFactory(unit).createEntityManager();
	}
}